import React from 'react';
import { observer, inject } from 'mobx-react';
import { withRouter } from 'react-router-dom';
import base from "../../util/base";
import { Icon } from 'weaver-mobile';
import { Tools } from 'weaver-mobile';
const getLabel = Tools.getLabel;
@inject('smartGuessStore')
@withRouter
@observer
export default class Main extends React.Component{
  
    constructor() {
      super();
      this.state = {
        initialTimer: null
      }
    }
   
    componentWillMount() {
      const { smartGuessStore, params } = this.props;
      const { dialog, initParams, baseReqParams } = smartGuessStore;
      if(!baseReqParams.requestid) {
        initParams(params);
      }
      if(dialog) dialog.close();
    }

    componentDidMount() {
      this.adjustWrapHeight();
      window.changeBtnStatus = this.changeBtnStatus;
      window.getinitialScale = this.getinitialScale; //获取嵌入iframe页面meta标签初始的initial-scale
      window.cancelLodingMask = this.cancelLodingMask;
    }
   
    componentDidUpdate() {
      const { smartGuessStatus } = base.smartGuessStore; 
      let headerObj = document.getElementsByClassName('wf-map-header')[0];
      let iframeObj = document.getElementById('smart-guess-map');
      if(iframeObj) {
        headerObj.onclick = function() {
          let panelObj = iframeObj.contentWindow.document.getElementById('wfFrontOperator-container');
          if(panelObj) {
            panelObj.style.visibility = 'hidden';
          }
        }
      }
      if(smartGuessStatus) {
        let headerObj = document.getElementsByClassName('wf-map-header')[0];
        headerObj.style.visibility = 'visible';
      } 
      this.adjustWrapHeight();
    }

    componentWillUnmount() {
      const{ smartGuessStore: {clearStore, timer} } = this.props;
      clearStore();
      timer && clearTimeout(this.initialTimer);
    }

    cancelLodingMask(loadingMaskStatus,opacity=false) {
      let loadingWrap = document.getElementsByClassName('map-box-show')[0].getElementsByClassName('loading-wrap')[0];
      if(loadingWrap) {
         loadingWrap.style.display = loadingMaskStatus;
         if(opacity) {
            loadingWrap.style.backgroundColor = 'transparent';
         } else {
           loadingWrap.style.backgroundColor = '#f4f4f4';
         }
      }
    }
    changeBtnStatus() {
      const { changeState } = base.smartGuessStore; 
      changeState({needBtnMask: false});
    }

    getinitialScale(val) {
      const { changeState, isFromDialog } = base.smartGuessStore; 
      let headerObj = document.getElementsByClassName('wf-map-header')[0];
      headerObj.style.visibility = 'visible';
      var viewport = document.getElementsByTagName("meta")["viewport"];
      if(isFromDialog) {
        viewport.setAttribute("content", "width=device-width, initial-scale=1, user-scalable=no");
        if(val >= 1) {
          val = 0.999;
        }
        changeState({recordScaleVal: val});
      } else {
        if(val >= 1) {
          val = 0.999;
        }
        viewport.setAttribute("content", "width=device-width, initial-scale=" + (val-0.001) +", maximum-scale= " + (val-0.001) + ", minimum-scale= " + (val-0.001));
        this.initialTimer = setTimeout(() => {
          this.initialTimer && clearTimeout(this.initialTimer);
          viewport.setAttribute("content", "width=device-width, initial-scale="+ val +", maximum-scale=5.0, minimum-scale=0.1, user-scalable=yes");
        }, 0);
        changeState({recordScaleVal: val, timer: this.initialTimer});
        this.cancelLodingMask('none');
      }
      
    }
    setMeta() {
      const { smartGuessStatus, allMapshow } = base.smartGuessStore; 
      if(!smartGuessStatus || allMapshow) {
        let that = this;
        const { recordScaleVal } = base.smartGuessStore; 
       this.Timer = setTimeout(() => {
        that.Timer && clearTimeout(that.Timer);
          var viewport = document.getElementsByTagName("meta")["viewport"];
          viewport.setAttribute("content", "width=device-width, initial-scale="+ recordScaleVal +", maximum-scale=5.0, minimum-scale=0.1, user-scalable=yes");
        }, 0);
      }
    }
   adjustWrapHeight() {
      let headerObj = document.getElementsByClassName('wf-map-header')[0];
      let height = headerObj && headerObj.offsetHeight;
      let wrapObj = document.getElementById('wf-map-container');
      let mapBox = document.getElementsByClassName('map-box')[0];
      wrapObj.style.height= 'calc(100% - ' + height + 'px)';
      let obj = document.getElementById('smart-guess-map');
      if(obj) {
        obj.style.height = mapBox.offsetHeight + 'px';
      }
    }
   openFoldPanel() {
    if( this.descriptWordBox.offsetHeight  == '30') {
      this.descriptWordBox.style.height = 'auto';
      this.descriptWordBox.style.overflow = 'unset';
      this.foldArrow.style.transform = 'rotate(180deg)';
    } else {
      this.foldArrow.style.transform = 'rotate(0)';
      this.descriptWordBox.style.height = '30px';
      this.descriptWordBox.style.overflow = 'hidden';
    }
   }
   getClass() {
     const { 
       smartGuessStatus, 
       needForecastFunc 
      } = this.props.smartGuessStore;
     if(needForecastFunc) {
        if(smartGuessStatus) {
          return 'descript-word-hidden'
        } else {
          return 'descript-word-show'
        }
      } else {
        return 'descript-word-show word-align-left'
      }
    }
   
    allBtnChange = (e) => {
      const { 
        changeState,
        allMapshow, 
        setRecordClicked, 
        recordScaleVal, 
        allViewRecordOnce
      } = this.props.smartGuessStore;
      let val = 0;
      setRecordClicked('all-btn-click');
      changeState({allMapshow: !allMapshow, isFromDialog: false});
      var viewport = document.getElementsByTagName("meta")["viewport"];
      if( recordScaleVal >= 1) {
       val = 0.999;
      } else {
       val = recordScaleVal;
      }
      if(allMapshow) {
        viewport.setAttribute("content", "width=device-width, initial-scale=1, maximum-scale=1,minimum-scale=1");
      } else {
        viewport.setAttribute("content", "width=device-width, initial-scale=" + (val-0.001) +", maximum-scale= " + (val-0.001) + ", minimum-scale= " + (val-0.001));
        this.setMeta();
      }
      if(allViewRecordOnce) {
        changeState({ allViewRecordOnce: false, 
                             allViewBtnFirstClick: true});
      } else {
        changeState({ allViewBtnFirstClick: false});
      }
    }
    smartBtnClick() {
      const { changeState, 
              smartGuessStatus, 
              setRecordClicked, 
              getForecastInfo,
              justDoOnce,  
              recordScaleVal,
              baseReqParams,
            } = this.props.smartGuessStore;
      let val = 0;
      if(justDoOnce) {
        changeState({
          justDoOnce: false,
          smartBtnFirstClick: true,
          needBtnMask: true
        });
        getForecastInfo(baseReqParams.requestid);
      } else {
        changeState({smartBtnFirstClick: false})
      }
     
      let loadingMask = document.getElementsByClassName('whole-map')[0];
      loadingMask.style.display = 'none';
      changeState({smartGuessStatus: !smartGuessStatus, allMapshow: false, isFromDialog: false})
      setRecordClicked('smart-btn-click');
      var viewport = document.getElementsByTagName("meta")["viewport"];
      if( recordScaleVal >= 1) {
        val = 0.999;
       } else {
        val = recordScaleVal;
       }
      if(smartGuessStatus) {
        viewport.setAttribute("content", "width=device-width, initial-scale=" + (val-0.001) +", maximum-scale= " + (val-0.001) + ", minimum-scale= " + (val-0.001));
        this.setMeta();
      } else {
        viewport.setAttribute("content", "width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1");
      }
    }
    //重新预测
    getForeCast() {
      const { smartGuessStore:{ changeState, getResetForecast } } = this.props;
      changeState({needShowTip: false, needBtnMask: true});
      let smartIframeWin = document.getElementById('smart-guess-map').contentWindow;
      smartIframeWin.getForecast(); //调用子页面中重新预测的方法
    }

    getInfo(info) { 
      let str = getLabel('515119', '于&date&&time&在$nodename$节点预测，');
      str = str.toLowerCase();
      if(typeof str === 'string' ) {
        str = str.replace('&date&', ' ' + info.forecastDate + ' ');
        str = str.replace('&time&', ' ' + info.forecastTime + ' ');
        str = str.replace('$nodename$', ' ' + '"' + info.forecastNodeName + '"')
        return str;
      } else {
        return '';
      }
    }
    getWranTip() {
      const { smartGuessStore, params} = this.props;
      const { forecastInfoMap, needShowTip, smartGuessStatus} = smartGuessStore;
      let forecastInfo = {};
      forecastInfo = forecastInfoMap.get(params.requestid);
      return (
        <div>
          {
              smartGuessStatus && needShowTip && forecastInfo && <div className='warn-top-info'>
              <p>
                <Icon type="anomaly" size={'xxs'} />
                {getLabel(515118,'当前流转由')}
                <a href={ `javaScript:openLink.openHrm(${forecastInfo.forecastUser})`} 
                  className='operator'>{forecastInfo.forecastUserName}</a>
                {this.getInfo(forecastInfo)}
                <a className={'reset-forecast-link'} onClick={this.getForeCast.bind(this)}>{getLabel(515120, '点击这里重新预测')}</a>
              </p>
            </div>
          }
        </div>
      )
    }
    getHeader() {
      const { 
        smartGuessStatus, 
        allMapshow, 
        needBtnMask, 
        needForecastFunc
      } = this.props.smartGuessStore
     return (
        [ 
          <div className='wrap-box top-btn-area'>
           {
              needForecastFunc 
              && <div className={smartGuessStatus? "btn active" : "btn"} onClick={this.smartBtnClick.bind(this)}>
                  <Icon type="intelligent-prediction" size={'xxs'} style={{ marginRight: '5px'}}/>
                  {getLabel(515100, '智能预测')}
                </div>
           }
            <div className={needBtnMask ? 'btn-mask' : ''}></div>
           { smartGuessStatus 
                && <div 
                  className = { needBtnMask ?  'not-allow-click btn' : 'btn all-view-btn' } 
                  onClick = { this.allBtnChange.bind(this) }
                >
                <span className = { allMapshow ? 'active' : ''} >
                  <Icon type="check" size={'xxs'} />
                </span>
                { getLabel(515101,'完整视图') }
              </div>
            }
           <div className={this.getClass()}
              ref = {ref => this.descriptWordBox = ref}
            >
            <div className='fold-arrow' 
              ref={ ref => this.foldArrow = ref}
              onClick={this.openFoldPanel.bind(this)} 
            >
              <Icon type="down" size={'xxs'} />
            </div>
            <div className='content-wrap'>
              <span className='passed-node'/>
              <p> { getLabel(515108, '已经过的节点')} </p>
            </div>
            <div className='content-wrap'>
              <span className='not-pass-node'/>
              <p> {getLabel(515105, '未经过节点')}</p>
            </div>
            <div className='content-wrap'>
              <span className='current-node'/>
              <p> {getLabel(515106, '当前节点')}</p>
            </div>
            <div className='content-wrap'>
              <span className='auto-pass-node'/>
              <p> {getLabel(515107, '异常跳过的节点')} </p>
            </div>
            <div className='content-wrap'>
              <span className='arrow passed-exit'>
                  <Icon type="play" size={'xxs'} />
              </span>
              <p> {getLabel(515277, '已经过的出口')}</p>
            </div>
            <div className='content-wrap'>
              <span className='arrow not-pass-exit'>
                  <Icon type="play" size={'xxs'} />
              </span>
              <p> {getLabel(515117, '未经过的出口')} </p>
            </div>
          </div>
         </div>,
         <React.Fragment>
            {smartGuessStatus &&  <div className='wrap-box bottom-description-area'> 
            <p>
              <span className='icon'>
                <Icon type="file-o" size={'xxs'} style={{position: 'relative', top: '2px'}}/>
              </span>
              {getLabel(515103, '可能会到达的节点')}
            </p>
            <p>
              <span className='icon arrow'>
                <Icon type="play" size={'xxs'} />
              </span>
              {getLabel(515264, '可能会经过的出口')}
            </p>
            </div>
          }
         </React.Fragment>
        ]
     )
    }
    render(){
        const { 
            smartGuessStatus, 
            allMapshow, 
            WholeMapPicSrc, 
            smartGuessPicSrc, 
            forecastMapSrc, 
            clickedMap, 
            smartBtnFirstClick, 
            allViewBtnFirstClick, 
            isFromDialog
        } = this.props.smartGuessStore;
        return (
          <div className='picture-container'>
            <div className="wf-map-header">
              { !allMapshow && smartGuessStatus && this.getWranTip()}
              {this.getHeader()}
              </div>
            <div id="wf-map-container" style={{backgroundColor: '#f4f4f4'}}>
               {/* 智能预测图 */}
                {
                  clickedMap.has('smart-btn-click') && <div  className={(smartGuessStatus && !allMapshow) ? 'map-box map-box-show': 'map-box-hidden'}>
                     { (smartBtnFirstClick || isFromDialog)&& <div className='loading-wrap' style={{backgroundColor: '#f4f4f4'}}>
                        <Icon type="loading" size={'md'}/>
                        </div> 
                      }
                    <iframe id={'smart-guess-map'} src={smartGuessPicSrc} style={{width:"100%", border:"none"}} />  
                  </div>
                  }
              {/* 完整流程图 */}
                 { <div className={!smartGuessStatus ? 'map-box map-box-show': 'map-box-hidden'}>
                    <div className='loading-wrap whole-map' style={{backgroundColor: '#f4f4f4'}}>
                        <Icon type="loading" size={'md'}/>
                    </div>
                  <iframe id={'whole-map'} src={WholeMapPicSrc} style={{width:"100%", height:"100%", border:"none"}} /> 
                </div>
                }
               {/* 预测流经流程图 */}
                { 
                  clickedMap.has('all-btn-click') && <div className={(smartGuessStatus&&allMapshow)  ? 'map-box map-box-show': 'map-box-hidden'}>
                     { allViewBtnFirstClick && <div className='loading-wrap' style={{backgroundColor: '#f4f4f4'}}>
                        <Icon type="loading" size={'md'}/>
                    </div>
                    }
                    <iframe className='forecast-map' src={forecastMapSrc} style={{ border: 0, width: '100%', height: '100%'}}></iframe>
                  </div>
                }
            </div>
          </div>
        )
    }

}
